Look.prototype._SITE_NAME = "追梦创游";
Look.prototype._PORTAL_DOMAIN = "/rest";
//Look.prototype._PORTAL_DOMAIN = "/rest2";
//Look.prototype._PORTAL_DOMAIN = "http://192.168.0.45:88/leyi";

var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-36297315-1']);
_gaq.push(['_setDomainName', 'dreamingame.com']);
_gaq.push(['_setAllowLinker', true]);
_gaq.push(['_trackPageview']);

$(document).ready(function(){
	try{
		$(window).hashchange(function(){
			look.loadFn();
		});
		$(window).hashchange();
	}catch(e){}
		
	var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
	$.getScript(gaJsHost + "google-analytics.com/ga.js", function(){
		try {console.log("GA get is success");}catch(e){}
	});
});

Look.prototype._USER_INFO = {
	SetUserName: function(userName){
		$.cookie("user_name", userName, {path : "/"});
	},
	GetUserName: function(){
		return $.cookie("user_name") ? $.cookie("user_name") : "";
	},
	DelUserName: function(){
		$.cookie("user_name", null, {path : "/"});
	},
	SetUID: function(uid){
		$.cookie("uid", uid, {path : "/"});
	},
	GetToken: function(){
		return $.cookie("ticket");
	}
};

Look.prototype.loadFn = function(theme, type){
    var theme = look.getHashParam("theme"), type = look.getHashParam("type");
    var typeArray = type.split("_");

  	if (theme == "login"){
		look.setTitle("Dream用户中心登录 - " + look._SITE_NAME);
		look.initLoader.loginLoader();
	} else if (theme == "recharge"){
		if (look.verify.forbidden()) {
			if (type == "choose_agent") {
				look.setTitle("选择要充值的游戏服务器 - " + look._SITE_NAME);
				look.initLoader.chooseAgentLoader();
			}else if (type == "recharge_set") {
				look.setTitle("游戏账号充值 - " + look._SITE_NAME);
				look.initLoader.rechargeSetLoader();
			}else if (type == "recharge_result") {
				look.initLoader.rechargeResultLoader();
			}
		}
	} else if (theme == ""){
		location.hash = "theme=login&type=login";
	}
}

Look.prototype.initLoader = {
	loginLoader: function(){
		if($("#loginWrapper").length == 0){
			look.loadPage("#main", "html/public/login.html");
			$("#userNameInput").focus();
		}
		$("#validateCodeImage").attr('src', look._IM10008.url);
		//[事件]确认登录
		$("#confirmLoginSubset").unbind("click").bind("click", function(){
			if($(this).hasClass("a_as_disabled")){return false;}
			var userName = $.trim($("#userNameInput").val()),
				password = $.trim($("#passwordInput").val()),
				validateCode = $.trim($("#validateCodeInput").val());
			if(userName == ""){look.showInfo.error("用户名不能为空");$("#userNameInput").focus();return false;}
			if(password == ""){look.showInfo.error("密码不能为空");$("#passwordInput").focus();return false;}
			if(validateCode == ""){look.showInfo.error("验证码不能为空");$("#validateCodeInput").focus();return false;}
			$("#confirmLoginSubset").addClass("a_as_disabled");
			loginRequest(userName, password, validateCode);
		});
		$("#userNameInput,#passwordInput").bind("keydown", function(){
			$("#loginTip").html("");
		});
		//[事件]更换验证码
		$("#changeValidateCodeSubset").unbind("click").bind("click", function(){
			$("#validateCodeImage").attr('src', look._IM10008.url + '?random=' + look.generateGuid());
		});
	},
	chooseAgentLoader: function(){
		if($("#chooseAgentWrapper").length == 0){
			look.loadPage("#main", "html/recharge/choose_agent.html");
			this.rechargeFn();
		}
		//[事件]选服
		$(".agent_subset").unbind("click").bind("click", function(){
			if ($(this).hasClass("disabled")) {return false;}
			if (look.requestCount.init("_im10004")) {
				var appid = $(this).attr("a_id"), serverId = $(this).attr("s_id");
				$(this).addClass("disabled");
				Look.prototype._TEMP = $(this);
				checkAppUserRequest(appid, serverId);
			}
		});
	},
	rechargeSetLoader: function(){
		if($("#rechargeSetWrapper").length == 0){
			look.loadPage("#main", "html/recharge/recharge_set.html");
			this.rechargeFn();
			//针对iOS 6.0的设备
			if(navigator.userAgent.toLowerCase().indexOf("os 6_0") != -1){
				$(".recharge_subset").before('<p class="color_red" style="padding-bottom:10px;font-weight:bold;">点下面的按钮时，如果不能打开支付宝支付页面，请来回切换浏览器标签一次。</p>');
			}
			//针对ie内核阻止弹出页面
			if(navigator.userAgent.toLowerCase().indexOf("ie") != -1){
				$(".recharge_subset").before('<p class="color_red" style="padding-bottom:10px;font-weight:bold;">点下面的按钮时，如果不能打开支付宝支付页面，请设置您的浏览器允许弹出窗口。</p>');
			}
		}
		var aTitle = $.cookie("a_title"), sTitle = $.cookie("s_title"), appid = $.cookie("c_appid"), serverId = $.cookie("c_server_id");
		if(appid && serverId){
			setTimeout(function(){
				$("#choosedAppCell").text($.cookie("a_title"));
				$("#choosedServerCell").text($.cookie("s_title"));
			}, 300);
			getUserPaymentInfoRequest(appid, serverId);
		}else{
			location.hash = look.setParam([["type", "choose_agent"]], location.hash);
		}
		//[事件]重新查询用户支付账户信息
		$("#regetUserPaymentInfoSubset").unbind("click").bind("click", function(){
			$(this).parent().hide().prev().show();
			getUserPaymentInfoRequest(appid, serverId);
		});
		//[事件]重新获取商品列表
		$("#regetPayItemSubset").unbind("click").bind("click", function(){
			$(this).hide();
			getPayItemRequest(appid);
		});
		//[事件]确认支付
		$("#confirmPaySubset").unbind("click").bind("click", function(){
			if($(this).hasClass("a_as_disabled")){return false;};
			var objValue = $("#payItemSelect option:selected").text().split(" = ");
			$.cookie('pay_price', objValue[0] + '元 （' + objValue[1] + '）');
			popError(
				'<div class="payment_info_check_poper recharge_poper">' +
				'	<div class="pop_content_word">' +
				'		<ul>' +
				'			<li><span class="left">账号信息：</span><b>' + aTitle + ' ' + sTitle + '</b></li>' +
				'			<li><span class="left">充值金额：</span><b>' + $.cookie('pay_price') +'</b></li>' +
				'		</ul>' +
				'	</div>' +
				'	<a href="javascript:" class="a_as_button" id="popConfirmPaySubset">进行支付</a>　<a href="javascript:clearPop();" class="a_as_button a_as_gray">取消</a>' +
				'</div>', '信息确认');
			$("#popConfirmPaySubset").unbind("click").bind("click", function(){
				if($(this).hasClass("a_as_disabled")){return false;}
				var productId = $("#payItemSelect option:selected").attr("p_id");
				if(!productId){look.showInfo.error("请选择一种充值额度");return false;}
				$(this).addClass("a_as_disabled");
				Look.prototype.redirectWindow = window.open('', '_blank');
				startPayRequest(appid, serverId, productId);
			}).focus();
		});
	},
	rechargeResultLoader: function(){
		if($("#rechargeResultWrapper").length == 0){
			look.loadPage("#main", "html/recharge/recharge_result.html");
			this.rechargeFn();
		}
		if($.cookie("payid")){
			checkPaymentRequest($.cookie("payid"));
		}else{
			$("#paymentDisabledPanel").show();
		}
	},
	//*************************************
	//* recharge公共方法
	//*************************************
	rechargeFn: function(){
		$("#userName").text(look._USER_INFO.GetUserName);
		//[事件]退出登录
		$("#logoutSubset").bind("click", function(){
			logoutRequest();
		});
	}
}

/*** Var START ***/
Look.prototype._IM10008 = {//获取验证码
	url : look._PORTAL_DOMAIN + "/uc/validate/code"
}
Look.prototype._IM10001 = {//登录
	url : look._PORTAL_DOMAIN + "/uc/v1/website/user/login",
	getJson : function(userName, password, validateCode){
		return 'userName=' + userName + '&pwd=' + password + '&validateCode=' + validateCode;
	}
}
Look.prototype._IM10002 = {//检查登录态
	url : look._PORTAL_DOMAIN + "/uc/v1/website/user/check_login"
}
Look.prototype._IM10003 = {//退出登录
	url : look._PORTAL_DOMAIN + "/uc/v1/website/user/logout"
}
Look.prototype._IM10004 = {//检查用户所在服
	url : look._PORTAL_DOMAIN + "/uc/v1/website/user/check_app_user",
	getJson : function(appid, serverId){
		return 'appid=' + appid + '&serverId=' + serverId;
	}
}
Look.prototype._IM10005 = {//取得用户当前支付账户信息
	url : look._PORTAL_DOMAIN + "/payment/payment/v1/website/user/payment_info",
	getJson : function(appid, serverId){
		return 'appid=' + appid + '&serverId=' + serverId;
	}
}
Look.prototype._IM10006 = {//获取商品列表
	url : look._PORTAL_DOMAIN + "/payment/payment/v1/website/pay/get_pay_item",
	getJson : function(appid){
		return 'appid=' + appid + '&group=leyi&store=alipayweb';
	}
}
Look.prototype._IM10007 = {//开始支付
	url : look._PORTAL_DOMAIN + "/payment/payment/v1/website/pay/start_payment",
	getJson : function(appid, serverId, productId){
		return 'appid=' + appid + '&serverId=' + serverId + '&productId=' + productId + '&group=leyi&agent=leyi&store=alipayweb';
	}
}
Look.prototype._IM10009 = {//检查支付状态
	url : look._PORTAL_DOMAIN + "/payment/payment/v1/website/pay/check_payment",
	getJson : function(payid){
		return 'payid=' + payid;
	}
}
Look.prototype._IM10010 = {//客服反馈
	url : look._PORTAL_DOMAIN + "/uc/v1/mis/cs/send_feed_back",
	getJson : function(appid, userName, email, content){
		return "appid=" + appid + "&locale=zh-Hans&userName=" + userName + "&email=" + email + "&description=" + content;
	}
}
/*** Var END ***/

/*** Request START ***/
//*************************************
//* 登录请求
//*************************************
function loginRequest(userName, password, validateCode){
	look.dataConn(look._IM10001.url, look._IM10001.getJson(userName, password, validateCode), loginCallback, loginComplete);
}
//*************************************
//* 检查登录态请求
//*************************************
function checkLoginRequest(){
	look.dataConn(look._IM10002.url, "", checkLoginCallback);
}
//*************************************
//* 退出登录请求
//*************************************
function logoutRequest(){
	look.dataConn(look._IM10003.url, "", logoutCallback);
}
//*************************************
//* 发送客服反馈请求
//*************************************
function sendFeedbackRequest(appid, userName, email, content){
	look.dataConn(look._IM10010.url, look._IM10010.getJson(appid, userName, email, content), sendFeedbackCallback, sendFeedbackComplete);
}
//*************************************
//* 检查用户所在服请求
//*************************************
function checkAppUserRequest(appid, serverId){
	look.dataConn(look._IM10004.url, look._IM10004.getJson(appid, serverId), checkAppUserCallback, checkAppUserComplete);
}
//*************************************
//* 取得用户当前支付账户信息请求
//*************************************
function getUserPaymentInfoRequest(appid, serverId){
	look.dataConn(look._IM10005.url, look._IM10005.getJson(appid, serverId), getUserPaymentInfoCallback);
}
//*************************************
//* 获取商品列表请求
//*************************************
function getPayItemRequest(appid){
	look.dataConn(look._IM10006.url, look._IM10006.getJson(appid), getPayItemCallback);
}
//*************************************
//* 获取商品列表请求
//*************************************
function startPayRequest(appid, serverId, productId){
	look.dataConn(look._IM10007.url, look._IM10007.getJson(appid, serverId, productId), startPayCallback, startPayComplete);
}
//*************************************
//* 检查支付状态请求
//*************************************
function checkPaymentRequest(payid){
	look.dataConn(look._IM10009.url, look._IM10009.getJson(payid), checkPaymentCallback);
}
/*** Request END ***/

/*** Callback START ***/
//*************************************
//* 登录callback
//*************************************
var loginCallback = function(back){
	if(back.data){
		look._USER_INFO.SetUserName(back.data.userName);
		$.cookie("redirect") ? location.hash = $.cookie("redirect") : location.hash = "theme=recharge&type=choose_agent";
	}
}
var loginComplete = function(){
	$("#confirmLoginSubset").removeClass("a_as_disabled");
	$("#validateCodeImage").attr('src', look._IM10008.url + '?random=' + look.generateGuid());
}
//*************************************
//* 检查登录态callback
//*************************************
var checkLoginCallback = function(back){
	
}
//*************************************
//* 退出登录callback
//*************************************
var logoutCallback = function(back){
	look._USER_INFO.DelUserName();
	look.verify.skip();
}
//*************************************
//* 发送客服反馈callback
//*************************************
var sendFeedbackCallback = function(back){
	look.showInfo.right("发送成功！感谢您的反馈…");
	$("#email,#content").val("");
}
var sendFeedbackComplete = function(){
	$("#confirmSendSubset").removeClass("a_as_disabled");
}
//*************************************
//* 检查用户所在服callback
//*************************************
var checkAppUserCallback = function(back){
	location.hash = look.setParam([["type", "recharge_set"]], location.hash);
	$.cookie("a_title", look._TEMP.attr("a_title"));
	$.cookie("s_title", look._TEMP.attr("s_title"));
	$.cookie("c_appid", look._TEMP.attr("a_id"));
	$.cookie("c_server_id", look._TEMP.attr("s_id"));
}
var checkAppUserComplete = function(){
	look._TEMP.removeClass("a_as_disabled");
}
//*************************************
//* 取得用户当前支付账户信息callback
//*************************************
var getUserPaymentInfoCallback = function(back){
	if (back.data.newBucks != undefined) {
		$("#currentBucksCell").text(back.data.newBucks);
		if($("#payItemSetCell").length != 0){
			getPayItemRequest($.cookie("c_appid"));
		}
	}else {
		$("#regetBucksCell").show().prev().hide();
	}
}
//*************************************
//* 获取商品列表callback
//*************************************
var getPayItemCallback = function(back){
	$("#payItemSetCell").fadeIn();
	if(back.data.items && back.data.items.length > 0){
		$.each(back.data.items, function(i){
			$("#payItemSelect").append(
				'<option value="' + back.data.items[i].bucks + '" p_id="' + back.data.items[i].productId + '" price="' + back.data.items[i].price + '">' + back.data.items[i].priceTitle + ' = ' + back.data.items[i].bucksTitle + '</option>'
			);
		});
		$("#confirmPaySubset").removeClass("a_as_disabled");
		var calculateAfterBucks = function(){
			return $("#afterPayBucksCell").text(parseInt($("#payItemSelect option:selected").val()) + parseInt($("#currentBucksCell").text()));
		}
		calculateAfterBucks();
		$("#payItemSelect").bind("change", function(){
			calculateAfterBucks();
		});
	}else{
		$("#regetPayItemSubset").show();
	}
}
//*************************************
//* 开始支付callback
//*************************************
var startPayCallback = function(back){
	if(back.data.redirect){
		$.cookie("payid", back.data.payid);
		popError(
			'<div class="payment_info_list_poper recharge_poper">' +
			'	<div class="pop_content_word">' +
			'		<ul>' +
			'			<li><span class="left">订单号：</span><b>' + back.data.payid + '</b></li>' +
			'			<li><span class="left">账号信息：</span><b>' + $.cookie("a_title") + ' ' + $.cookie("s_title") + '</b></li>' +
			'			<li><span class="left">充值金额：</span><b>' + $.cookie('pay_price') + '</b></li>' +
			'		</ul>' +
			'	</div>' +
			'	<a href="javascript:" class="a_as_button" id="popConfirmFinishSubset">已经完成支付，进行确认</a>　<a href="javascript:clearPop();" class="a_as_button" id="popBackPaymentSubset">出现问题，返回充值页面</a>' +
			'</div>', '当前订单信息');
		//[事件]充值失败，关闭新开的页面redirectWindow
		$("#popBackPaymentSubset").unbind("click").bind("click", function(){
			look.redirectWindow.close();
		});
		//[事件]检查充值状态
		$("#popConfirmFinishSubset").unbind("click").bind("click", function(){
			if(look.redirectWindow){look.redirectWindow.close();}
			location.hash = look.setParam([["type", "recharge_result"]], location.hash);
			clearPop();
		}).focus();
		look.redirectWindow.location = encodeURI(back.data.redirect);
	}
}
var startPayComplete = function(){
	$("#popConfirmPaySubset").removeClass("a_as_disabled");
}
//*************************************
//* 检查支付状态callback
//*************************************
var checkPaymentCallback = function(back){
	if(back.data.state != undefined){
		var payState = back.data.state,
			appid = $.cookie("c_appid"),
			payid = $.cookie("payid"),
			appTitle = $.cookie("a_title"),
			serverTitle = $.cookie("s_title");
		$(".service_gateway_subset").attr('href', '#theme=game&type=game&appid=' + appid + '&feedback=true');
		$(".payid_cell").text(payid);
		$(".app_server_cell").text(appTitle + "　" + serverTitle);
		$(".pay_price_cell").text($.cookie("pay_price"));
		//[事件]重新检测支付状态
		$("#refreshSubset").bind("click", function(){
			if (look.requestCount.init("_im10009")) {
				checkPaymentRequest(payid);
			}
		});
		switch(payState){
			case "0" : 
			case "2" : 
			case "3" : 
				look.setTitle("充值未完成 - " + appTitle + " - " + serverTitle + " - " + look._SITE_NAME);
				$("#paymentUnfinishPanel").show();
				break;//未完成
			case "1" :
			case "4" :
				look.setTitle("充值失败 - " + appTitle + " - " + serverTitle + " - " + look._SITE_NAME);
				$("#paymentFailPanel").show();
				break;//失败
			case "5" : 
			case "6" : 
				look.setTitle("充值成功 - " + appTitle + " - " + serverTitle + " - " + look._SITE_NAME);
				$("#paymentSuccessPanel").show();
				getUserPaymentInfoRequest(appid, $.cookie("c_server_id"));
				$("#closeWindowSubset").bind("click", closeWindow);
				break;//成功
			default : location.hash = look.setParam([["type", "choose_agent"]], location.hash);
		}
	}
}
/*** Callback END ***/

/**
 * 安全验证
 */
Look.prototype.verify = {
	init : function(){
		return look._USER_INFO.GetToken();
	},
	forbidden : function(){
		if(!look.verify.init()) {
			$.cookie("redirect", window.location.hash.split("#")[1].substring(0));
			window.location.hash = "theme=login&type=login";
			return false;
		}
		return true;
	},
	skip : function(){
		if(!look.verify.init()) {
			window.location.href = "index.html";
			return false;
		}
	}
};